package cn.itcast.service.cargo.impl;

import cn.hutool.core.util.IdUtil;
import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.cargo.ContractProductDao;
import cn.itcast.dao.cargo.ExtCproductDao;
import cn.itcast.domain.cargo.*;
import cn.itcast.domain.vo.ContractProductVo;
import cn.itcast.service.cargo.ContractService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ContractServiceImpl implements ContractService {


    @Autowired
    private ContractDao contractDao;
    @Autowired
    private ExtCproductDao extCproductDao;
    @Autowired
    private ContractProductDao contractProductDao;

    @Override
    public Contract findById(String id) {
        return contractDao.selectByPrimaryKey(id);
    }

    @Override
    public void save(Contract contract) {
       //指定合同主键Id
        contract.setId(IdUtil.simpleUUID());
        contract.setState(0);//草稿
        contractDao.insertSelective(contract);
    }

    @Override
    public void update(Contract contract) {
        contractDao.updateByPrimaryKeySelective(contract);
    }

    @Override
    public void delete(String id) {
        //删除附件
        ExtCproductExample extcExample = new ExtCproductExample();
        ExtCproductExample.Criteria extcCriteria = extcExample.createCriteria();
        extcCriteria.andContractIdEqualTo(id);
        //条件查询
        List<ExtCproduct> extCproducts = extCproductDao.selectByExample(extcExample);

        for (ExtCproduct extCproduct : extCproducts) {
            extCproductDao.deleteByPrimaryKey(extCproduct.getId());
        }

        //删除货物
        ContractProductExample cpExample = new ContractProductExample();
        ContractProductExample.Criteria cpCriteria = cpExample.createCriteria();
        cpCriteria.andContractIdEqualTo(id);
        //条件查询
        List<ContractProduct> list = contractProductDao.selectByExample(cpExample);

        for (ContractProduct contractProduct : list) {
            contractProductDao.deleteByPrimaryKey(contractProduct.getId());
        }

        //删除合同
       contractDao.deleteByPrimaryKey(id);
    }

    @Override
    public List<Contract> findAll(ContractExample example) {
        return contractDao.selectByExample(example);
    }

    @Override
    public PageInfo findByPage(int pageNum, int pageSize, ContractExample example) {
        PageHelper.startPage(pageNum, pageSize);
        List<Contract> list = contractDao.selectByExample(example);
        return new PageInfo(list);
    }

    @Override
    public List<ContractProductVo> findContractProductVo(String companyId, String shipTime) {
        return contractDao.findContractProductVo(companyId,shipTime);
    }
}
